//
//  IndexViewController.swift
//  麦子洗衣  首页
//
//  Created by yangyifan on 15/10/21.
//  Copyright © 2015年 womenshuo. All rights reserved.
//

import UIKit
import SwiftyUserDefaults

class IndexViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet   var adScrollView: UIScrollView!//广告 ScrollView
    @IBOutlet   var adPage: UIPageControl!//广告pageController
    
    private     var bounds: CGRect          = UIScreen.mainScreen().bounds//屏幕大小
    private     var adImageArray: [String]  = ["index_ad_02", "index_ad_02", "index_ad_02"]//广告
    
    let adScroViewHieght: CGFloat       = 144 //广告 ScrollView 高度
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化
        self.initialize()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        //设置广告 ScrollView
        self.setAdScrollView()

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //打开首页 初始化操作
    private func initialize() -> Bool {
        
        //获取 "isFrist"
        let isFirst = Defaults[.isFrist]        
        if  isFirst == false  {
            //跳转待启动界面
            self.navigationController?.pushViewController(Redirect.redirectToStart(), animated: true)
            //设置 "isFrist" 为true
            Defaults[.isFrist] = true
            return true
        }
        
        //判断是否已经登录
        let isLogin = Defaults[.isLogin]
        
        //如果没有登录，则跳转到登录页面
        if isLogin == false {
            self.navigationController?.pushViewController(Redirect.redirectToLogin(), animated: true)
            return true
        }
        return true
    }
    
    //设置广告 ScrollView
    private func setAdScrollView() {
        adScrollView.contentSize                    = CGSize(width: self.bounds.width * CGFloat(self.adImageArray.count), height: adScroViewHieght)
        adScrollView.showsHorizontalScrollIndicator = false
        adScrollView.showsVerticalScrollIndicator   = false
        
        //设置ScrollView Delegate
        adScrollView.delegate = self
        
        //添加广告到adScrollView
        for index in 0..<self.adImageArray.count {
            let imageView   = UIImageView(frame: CGRect(x: self.bounds.width * CGFloat(index), y: 0, width: self.bounds.width, height: adScroViewHieght))
            imageView.image = UIImage(named: self.adImageArray[index])
            adScrollView.addSubview(imageView)
        }
        
    }
    
    //广告 ScrollView 滚动时
    func scrollViewDidScroll(scrollView: UIScrollView) {
        adPage.currentPage = Int(scrollView.contentOffset.x / self.bounds.width)
    }
    
    

}
